package com.qf.ability.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.ability.auth.service.AuthService;
import com.qf.business.user.feign.UserFeign;
import com.qf.commons.core.utils.JwtUtils;
import com.qf.data.auth.vo.WXAuthInput;
import com.qf.data.user.entity.User;
import com.qf.data.user.vo.input.WXUserInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
@Slf4j
public class WXAuthServiceImpl implements AuthService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String wxlogin(WXAuthInput wxAuthInput) {
        //http请求，请求微信服务器获取用户的凭证（open_id/session_key）
//        Map<String,String> params = new HashMap<>();
//        params.put("appid","wxb40be8f6e777aa17");wxb40be8f6e777aa17
//        params.put("secret","c490824145970140c24920d26c8c752b");
//        params.put("js_code",wxAuthInput.getCode());
//        params.put("grant_type","authorization_code");

        String result = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=wxb40be8f6e777aa17&secret=c490824145970140c24920d26c8c752b&js_code=" + wxAuthInput.getCode() + "&grant_type=authorization_code", String.class);
        log.info("[wxlogin] - 获取到微信的登录凭证 - {}",result);

        //转换成json对象
        JSONObject jsonObject = JSON.parseObject(result);
        String sessionKey = jsonObject.getString("session_key");
        String openId = jsonObject.getString("openid");

        WXUserInput wxUserInput = new WXUserInput();
        wxUserInput.setOpenId(openId);
        wxUserInput.setSessionKey(sessionKey);
        wxUserInput.setHeader(wxAuthInput.getHeader());
        wxUserInput.setNickName(wxAuthInput.getNickname());


        //调用用户微服务，将当前的数据同步到数据库中
        User user = userFeign.wxUserQuery(wxUserInput).result();

        //根据登录的用户信息，生成一个jwt的令牌，将令牌返回给客户端保存
        String jwtToken = JwtUtils.createJwtToken(user.getId());
        return jwtToken;
    }
}
